package com.ct.ah.lab.service.impl;

import com.ct.ah.lab.dao.UserDao;
import com.ct.ah.lab.entity.User;
import com.ct.ah.lab.exception.UserException;
import com.ct.ah.lab.service.IUserService;
import com.ct.ah.lab.util.CodeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service("UserService")
public class UserSerivceImpl implements IUserService {
    @Autowired
    private UserDao userDao;

    @Override
    public Boolean checkUsername(String username) {
        int count = userDao.getByUserName(username);
        if(count > 0) {
            return true;
        }
        else {
            return false;
        }
    }

    @Override
    public void regist(User user) {
        String newPassword = CodeUtil.getMD5Encoding(user.getPassword());
        user.setPassword(newPassword);
        userDao.regist(user);
    }

    @Override
    public User login(String username, String password) {
        User user = userDao.login(username);
        if(user == null){
            throw new UserException("用户名不存在");
        }
        if(!CodeUtil.getMD5Encoding(password).equals(user.getPassword())) {
            throw new UserException("密码错误");
        }
        return user;
    }

    @Override
    public void changePassword(User loginUser, String oldPassword, String newPassword) {
        User user = userDao.login(loginUser.getUsername());
        if(user == null){
            throw new UserException("用户名不存在");
        }
        if(!CodeUtil.getMD5Encoding(oldPassword).equals(user.getPassword())) {
            throw new UserException("密码错误");
        }
        user.setPassword(CodeUtil.getMD5Encoding(newPassword));
        userDao.changePassword(user);
    }

    @Override
    public User findUserInfoByName(String username) {
        User user = userDao.login(username);
        if(user == null){
            throw new UserException("用户名不存在");
        }
        user.setPassword("");
        return user;
    }

    @Override
    public void changeUserInfo(User updateUser) {
        userDao.changeUserInfo(updateUser);
    }


}
